package com.tanxiuxin.YiWaiMai.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanxiuxin.YiWaiMai.common.Result;
import com.tanxiuxin.YiWaiMai.pojo.User;
import com.tanxiuxin.YiWaiMai.service.UserService;
import com.tanxiuxin.YiWaiMai.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     *   发送手机短信验证码
     * @return
     */
    @PostMapping("/sendMsg")
    public Result<String> sendMsg(@RequestBody User user , HttpSession session ){

        // 获取手机号
        String phone = user.getPhone();

        if (StringUtils.isNotEmpty(phone)){
            // 生成随机的四位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code->" + code);
            // 调用阿里云提供的短信服务 API 完成发送短信
            // SMSUtils.sendMessage("易外卖" , "" , phone , code);

            // 需要将生成的验证码保存到 Session
            // session.setAttribute(phone , code);

            // 将生成的验证码缓存到redis中，并且设置有效期为 5 分钟
            redisTemplate.opsForValue().set(phone , code , 5 , TimeUnit.MINUTES);

            return Result.success("手机验证码短信发送成功");
        }
        return Result.error("短信验证码发送失败");
    }

    /**
     *   移动端登录
     * @return
     */
    @PostMapping("/login")
    public Result<User> login(@RequestBody Map map, HttpSession session ){

        // 获取手机号
        String phone = map.get("phone").toString();

        // 获取验证码
        Object code = map.get("code");

        // 从 Session 中获取保存的验证码
        // Object codeInSession = session.getAttribute(phone);

        // 从 redis 中来获取缓存的验证码
        Object codeInSession = redisTemplate.opsForValue().get(phone);
        // 进行验证码的比对
        if (codeInSession != null && codeInSession.equals(code)) {
            // 对比成功，则说明登陆成功
                LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(User::getPhone , phone);
                User user = userService.getOne(queryWrapper);
            // 判断当前手机号对应的用户是否为新用户，如果是新用户就自动注册
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                userService.save(user);
            }
            session.setAttribute("user" , user.getId());

            // 如果用户登陆成功，删除 redis 缓存中的验证码
            redisTemplate.delete(phone);

            return Result.success(user);
        }
        return Result.error("登陆失败");
    }

    /**
     * 退出登录
     * @return
     */
    @PostMapping("/loginout")
    public Result<String> logOut(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return Result.success("登出成功");
    }
}
